package me.jessyan.mvparms.demo.mvp.ui.activity.specialoffer;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.jessyan.mvparms.demo.R;
import me.jessyan.mvparms.demo.di.component.specialoffer.DaggerLongPicComponent;
import me.jessyan.mvparms.demo.di.module.specialoffer.LongPicModule;
import me.jessyan.mvparms.demo.mvp.contract.specialoffer.LongPicContract;
import me.jessyan.mvparms.demo.mvp.presenter.specialoffer.LongPicPresenter;
import me.jessyan.mvparms.demo.mvp.ui.widget.CustomToolbar;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * 活动详情webView页面
 * //https://blog.csdn.net/qq_17766199/article/details/71698593
 //https://www.kotlintc.com/articles/5470
 */
public class LongPicActivity extends BaseActivity<LongPicPresenter> implements LongPicContract.View {


    /**
     * manager
     */
    private CookieManager cookieManager = CookieManager.getInstance();


    /**
     * 加载网址
     */
    private String path;
    /**
     * 参数
     */
    private Map<String, String> map;

    @BindView(R.id.toolbar)
    CustomToolbar toolbar;
    @BindView(R.id.webview)
    WebView bidWebview;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLongPicComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .longPicModule(new LongPicModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_long_pic; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        toolbar.setRightIv(R.drawable.ic_share);
        toolbar.setListener(new CustomToolbar.ToolbarListener() {
            @Override
            public void onLeftBack() {
                killMyself();
            }

            @Override
            public void onRightBack() {
                // TODO: 2019/3/6 0006  分享 
            showMessage("分享");
            }
        });

        initWeb();
    }
    /**
     * init
     */
    private void initWeb() {
        bidWebview = findViewById(R.id.webview);



        path = "https://www.baidu.com";


        bidWebview.getSettings().setAllowFileAccess(true);  //应许读取文件
        bidWebview.getSettings().setJavaScriptEnabled(true);
        bidWebview.getSettings().setAppCacheEnabled(true);
        bidWebview.getSettings().setDomStorageEnabled(true);
        bidWebview.getSettings().setBlockNetworkImage(false);
        bidWebview.getSettings().setUseWideViewPort(true);
        bidWebview.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
//                if (mMDialog == null) {
//                    mMDialog = new LoadingDialog(context);
//                    mMDialog.setCancelable(true);
//                    mMDialog.setCanceledOnTouchOutside(false);
//                    mMDialog.show();
//                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

//                try {
//                    mBidWebview.loadUrl("javascript:orderStatus()");
//                } catch (Exception e) {
//
//                }


//                if (refresh != null && refresh.isRefreshing()) {
//                    refresh.setRefreshing(false);
//                }
//                if (mMDialog != null && mMDialog.isShowing()) {
//                    mMDialog.dismiss();
//                }
            }

            //
            @SuppressWarnings("deprecation")
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Log.d("网络", failingUrl + "\n" + errorCode + "   " + description);


                view.loadUrl("file:///android_asset/error.html");
            }

            //
            @TargetApi(android.os.Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
                onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
            }

        });
        bidWebview.setWebChromeClient(new WebChromeClient() {
            /**
             * 当WebView加载之后，返回 HTML 页面的标题 Title
             * @param view
             * @param title
             */

            @Override
            public void onReceivedTitle(WebView view, String title) {
                //判断标题 title 中是否包含有“error”字段，如果包含“error”字段，则设置加载失败，显示加载失败的视图
                if (!TextUtils.isEmpty(title) && title.toLowerCase().contains("error")) {

                    if (bidWebview != null) {
                        bidWebview.loadUrl("file:///android_asset/error.html");
                    }

                }
            }
        });

        map = new HashMap<>();
//        mMap.put("token", UserManager.getIns().getUser().getToken());

        cookieManager.setAcceptCookie(true);
//        SharedPreferences mPreferences = App.getInst().getSharedPreferences("cookie", 0);
//        String temp = mPreferences.getString("cookie", "");
//        cookieManager.setCookie(basePath + "user/tender/tenderCacheInfo/", temp);
        CookieSyncManager.getInstance().sync();
//        mBidWebview.addJavascriptInterface(new JavaScriptObject(), "JSBridge");




//        if (!NetworkUtils.isConnected()) {
//            failed(new UiThrowable("当前网络不可用"));
//            //   mBidWebview.loadUrl("fileerror.html:///android_asset/error.html");
//        }
//        else {


            bidWebview.loadUrl(path, map);
//            refresh.setRefreshing(true);   //设置正在刷新
//        }
    }

    @Override
    protected void onDestroy() {

        if (bidWebview != null) {//解决内存泄露
            bidWebview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            bidWebview.clearHistory();

            ((ViewGroup) bidWebview.getParent()).removeView(bidWebview);
            bidWebview.stopLoading();
            bidWebview.setWebChromeClient(null);
            bidWebview.setWebViewClient(null);
            bidWebview.destroy();
            bidWebview = null;
        }
        super.onDestroy();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }


}
